<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-position="middle"
             label-width="100px"
    >
      <el-form-item label="样本复份编号" prop="sampBackupCode">
        <el-input
          v-model="queryParams.sampBackupCode"
          clearable
          placeholder="请输入样本复份编号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="样本类型" prop="sampTypeId">
        <treeselect v-model="queryParams.sampTypeId" :normalizer="normalizerSampType" :options="sampleTypeOptions"
                    placeholder="请选择样本类型" size="small" style="width: 214px; height: 32px"
        />
      </el-form-item>
      <el-form-item label="样本组" prop="sampGroupId">
        <treeselect v-model="queryParams.sampGroupId" :normalizer="normalizerSampGroup" :options="sampleGroupOptions"
                    placeholder="请选择样本组" size="small" style="width: 214px"
        />
      </el-form-item>
      <el-form-item label="样本状态" prop="sampState">
        <el-select
          v-model="queryParams.sampState"
          clearable
          placeholder="样本状态"
          size="small"
          style="width: 214px"
        >
          <el-option
            v-for="dict in sampStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="条码/二维码" prop="qrCode">
        <el-input
          v-model="queryParams.qrCode"
          clearable
          placeholder="样本条码/二维码"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="样本源编号" prop="sourceCode">
        <el-input
          v-model="queryParams.sourceCode"
          clearable
          placeholder="请输入样本源编号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="样本源名称" prop="sourceName">
        <el-input
          v-model="queryParams.sourceName"
          clearable
          placeholder="请输入样本源名称"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="样本源类型" prop="sourceTypeId">
        <treeselect v-model="queryParams.sourceTypeId" :normalizer="normalizerSourceType" :options="sourceTypeOptions"
                    placeholder="请选择样本源类型" size="small" style="width: 214px"
        />
      </el-form-item>
      <el-form-item label="采样时间" prop="samplingRange">
        <el-date-picker
          v-model="queryParams.samplingRange"
          :picker-options="pickerOptions"
          align="right"
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          style="width: 360px"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleCreate"
        >创建新样本
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:print']"
          icon="el-icon-printer"
          plain
          size="mini"
          type="success"
          @click="handlePrint"
        >打印条码
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:import']"
          icon="el-icon-upload2"
          plain
          size="mini"
          type="info"
          @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:export']"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sampleList" max-height="630" size="small"
              @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="样本复份编号" min-width="110" prop="sampBackupCode"/>
      <el-table-column align="center" label="样本类型" prop="sampTypeName"/>
      <el-table-column align="center" label="样本源名称" prop="sampSourceName"/>
      <el-table-column align="center" label="采样时间" prop="samplingTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.samplingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="样本位置" prop="sampLocation" width="300"/>
      <el-table-column align="center" label="样本源类型" prop="sampSourceTypeName"/>
      <el-table-column align="center" label="样本组" prop="sampGroupName"/>
      <el-table-column align="center" label="样本量" prop="sampQuantity"/>
      <el-table-column align="center" label="样本单位" prop="sampUnit"/>
      <el-table-column :formatter="sampStateFormat" align="center" label="样本状态" prop="sampState"/>
      <el-table-column align="center" label="冻融次数" prop="sampFreezeThawCount"/>
      <el-table-column align="center" label="条码/二维码" prop="qrCode"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['biobank:sample:query']"
            icon="el-icon-view"
            size="mini"
            type="text"
            @click="handleView(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 创建新样本 -->
    <el-dialog :visible.sync="createOpen" append-to-body title="创建新样本" width="60%">
      <el-form ref="createForm" :model="createForm" :rules="createRules" label-width="96px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="样本源编号" prop="sourceCode">
              <el-input v-model="createForm.sourceCode" placeholder="请输入样本源编号" @change="getSourceDetail"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="样本源名称" prop="sourceName">
              <el-input v-model="createForm.sourceName" placeholder="请输入样本源名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="随访状态" prop="followState">
              <el-select
                v-model="createForm.followState"
                clearable
                placeholder="随访状态"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in followStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="样本源类型" prop="sourceTypeId">
              <treeselect v-model="createForm.sourceTypeId" :normalizer="normalizerSourceType"
                          :options="sourceTypeOptions" placeholder="请选择样本源类型"
                          @select="sourceTypeSelect"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="样本源描述" prop="sourceDesc">
              <el-input v-model="createForm.sourceDesc" :rows="2" placeholder="请输入样本源描述" type="textarea"></el-input>
            </el-form-item>
            <el-input v-if="false" v-model="createForm.formKey" placeholder="请输入自定义表单key"/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div
              v-for="(domain, index) in createForm.formJson"
              :key="index"
              :label="domain.controlLable"
            >
              <parser ref="formCustom" :form-conf="domain.json"/>
            </div>
          </el-col>
        </el-row>
        <file-upload :value="createForm.attaches" style="margin-top: 16px" @fileEvent="fileUploadEvent"></file-upload>
        <el-divider><i class="el-icon-s-promotion"></i></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="样本类型" prop="sampTypeId">
              <treeselect v-model="createForm.sampTypeId" :normalizer="normalizerSampType" :options="sampleTypeOptions"
                          placeholder="请选择样本类型"
                          @select="sampleTypeSelect"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="样本组" prop="sampGroupId">
              <treeselect v-model="createForm.sampGroupId" :normalizer="normalizerSampGroup"
                          :options="sampleGroupOptions" placeholder="请选择样本组"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="样本量" prop="sampQuantity">
              <el-input v-model="createForm.sampQuantity" oninput="value=value.replace(/[^0-9.]/g,'')"
                        placeholder="请输入样本量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="样本单位" prop="sampUnit">
              <el-input v-model="createForm.sampUnit" placeholder="请输入样本单位"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="样本复份数" prop="sampBackupCount">
              <el-input-number v-model="createForm.sampBackupCount" :min="1" controls-position="right"
                               oninput="value=value.replace(/[^0-9]/g,'')" placeholder="请输入样本复份数" style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="冻存管类型" prop="tubeType">
              <el-select
                v-model="createForm.tubeType"
                clearable
                placeholder="冻存管类型"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in tubeTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采样时间" prop="samplingTime">
              <el-date-picker v-model="createForm.samplingTime" clearable
                              placeholder="选择采样时间"
                              size="small"
                              style="width: 100%"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCreateForm">确 定</el-button>
        <el-button @click="cancelCreate">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看样本复份 对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="70%">

      <div class="scrollbar" style="height:600px;">
        <el-scrollbar style="height:100%">
          <el-row>
            <el-col :span="7">
              <div>
                <label class="samp-label">样本复份编号 </label>
                <span class="samp-value">{{ form.sampBackupCode }}</span>
              </div>
              <div>
                <span class="samp-label">样本状态 </span>
                <span class="samp-value">{{ sampStateFormat(form) }}</span>
              </div>
              <div>
                <span class="samp-label">样本量 </span>
                <span class="samp-value">{{ form.sampQuantity }}</span>
              </div>
              <div>
                <span class="samp-label">样本单位 </span>
                <span class="samp-value">{{ form.sampUnit }}</span>
              </div>
              <div>
                <span class="samp-label">格式化位置 </span>
                <span class="samp-value">{{ form.sampLocation }}</span>
              </div>
              <div>
                <span class="samp-label">冻融次数 </span>
                <span class="samp-value">{{ form.sampFreezeThawCount }}</span>
              </div>
              <div>
                <span class="samp-label">采样时间 </span>
                <span class="samp-value">{{ form.samplingTime }}</span>
              </div>
              <div>
                <span class="samp-label">条码/二维码 </span>
                <span class="samp-value">{{ form.qrCode }}</span>
              </div>
              <div>
                <span class="samp-label">贴码管/预置管 </span>
                <span class="samp-value">{{ tubeTypeFormat(form) }}</span>
              </div>
            </el-col>
            <el-col :span="0.5">
              <el-divider direction="vertical"></el-divider>
            </el-col>
            <el-col :span="8">
              <div>
                <span class="samp-label">样本源编号</span>
                <span class="samp-value">{{ sampSourceInfo.sourceCode }}</span>
              </div>
              <div>
                <span class="samp-label">样本源类型 </span>
                <span class="samp-value">{{ sampSourceInfo.sourceTypeName }}</span>
              </div>
              <div>
                <span class="samp-label">样本源名称 </span>
                <span class="samp-value">{{ sampSourceInfo.sourceName }}</span>
              </div>
              <div>
                <span class="samp-label">样本源描述 </span>
                <span class="samp-value">{{ sampSourceInfo.sourceDesc }}</span>
              </div>
              <div>
                <span class="samp-label">随访状态 </span>
                <span class="samp-value">{{ followStateFormat(sampSourceInfo) }}</span>
              </div>
              <el-collapse v-model="activeNames">
                <el-collapse-item :name="1">
                  <!-- <template slot="title">自定义表单<i class="el-icon-s-promotion"></i></template> -->
                  <el-divider><i class="el-icon-s-promotion"></i></el-divider>
                  <div
                    v-for="(domain, index) in form.formJson"
                    :key="index"
                    :label="domain.controlLable"
                  >
                    <parser ref="formCustom" :form-conf="domain.json"/>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-col>
            <el-col :span="0.5">
              <el-divider direction="vertical"></el-divider>
            </el-col>
            <el-col :span="8">
              <!-- 生命周期 -->
              <el-timeline :reverse="reverse">
                <el-timeline-item
                  v-for="(activity, index) in lifeCycles"
                  :key="index"
                  :timestamp="activity.updateTime"
                >
                  {{ activity.typeName }} - {{ activity.createName }}
                </el-timeline-item>
              </el-timeline>
            </el-col>
          </el-row>
          <el-divider content-position="center">同样本其他复份信息</el-divider>
          <el-table :data="sameSamples" max-height="280" size="small">
            <el-table-column align="center" label="复份编号" prop="sampBackupCode" width="150"/>
            <el-table-column align="center" label="样本位置" prop="sampLocation" width="450"/>
            <el-table-column align="center" label="条码/二维码" prop="qrCode"/>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-scrollbar>
      </div>
    </el-dialog>
    <!-- 样本导入 对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" append-to-body width="400px">
      <el-upload
        ref="upload"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的样本源
          <el-link style="font-size:12px" type="info" @click="importTemplate">下载模板</el-link>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addSample,
  createSample,
  exportSample,
  getImportTemplate,
  getSameSamples,
  getSample,
  getSampleLifeCycle,
  getSampSourceInfo,
  listSample,
  updateSample
} from '@/api/biobank/sample'
import { getSampleType, listSampleType } from '@/api/biobank/sampleType'
import { listSampleGroup } from '@/api/biobank/sampleGroup'
import { listSourceType } from '@/api/biobank/sourceType'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getSourceByCode } from '@/api/biobank/source'
import { formJsonShow } from '@/api/tool/form'
import { getToken } from '@/utils/auth'
import { getActiveTemp } from '@/api/tool/labelTemp'
import Parser from 'form-gen-parser'
import FileUpload from '@/components/FileUpload'

export default {
  name: 'SampleList',
  components: {
    Treeselect,
    Parser,
    FileUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组id
      ids: [],
      // 选中数组
      selectSamples: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 样本复份 表格数据
      sampleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 创建样本弹出层
      createOpen: false,
      // 样本数据导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的样本源
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/biobank/sample/importData'
      },
      sourceOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'DESC',
        sampBackupCode: undefined,
        sampState: undefined,
        sampTypeId: undefined,
        sampGroupId: undefined,
        sourceCode: undefined,
        sourceName: undefined,
        sourceTypeId: undefined,
        samplingRange: undefined
      },
      // 样本类型 树选项
      sampleTypeOptions: [],
      // 样本组 树选项
      sampleGroupOptions: [],
      // 样本源类型 树选项
      sourceTypeOptions: [],
      // 样本状态
      sampStateOptions: [],
      // 随访状态
      followStateOptions: [],
      // 冻存管类型
      tubeTypeOptions: [],
      // 启用的打印标签模板
      activeLabelTemp: {},
      // 表单参数
      form: {},
      reverse: true,
      // 样本生命周期
      lifeCycles: [],
      // 同样本其他复份
      sameSamples: [],
      // 样本源信息
      sampSourceInfo: {},
      //自定义表单折叠面板默认展开值
      activeNames: 1,
      // 创建样本表单参数
      createForm: {},
      // 表单校验
      rules: {},
      // 创建新样本表单校验
      createRules: {
        sourceCode: [{ required: true, trigger: 'blur', message: '样本源编号不能为空' }, {
          max: 50,
          trigger: 'blur',
          message: '样本源编号不能超过50个字符'
        }],
        sourceName: [{ required: true, trigger: 'blur', message: '样本源名称不能为空' }, {
          max: 50,
          trigger: 'blur',
          message: '样本源名称不能超过50个字符'
        }],
        sourceDesc: { max: 100, trigger: 'blur', message: '样本源描述不能超过100个字符' },
        sourceTypeId: { required: true, trigger: 'change', message: '样本源类型不能为空' },
        sampTypeId: { required: true, trigger: 'change', message: '样本类型不能为空' },
        sampGroupId: { required: true, trigger: 'change', message: '样本组不能为空' },
        sampBackupCount: { required: true, trigger: 'blur', message: '样本复份数不能为空' },
        tubeType: { required: true, trigger: 'change', message: '冻存管类型不能为空' }
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.getDicts('sample_state').then(response => {
      this.sampStateOptions = response.data
    })
    this.getList()
    this.getSampleTypeList()
    this.getSampleGroupList()
    this.getSourceTypeList()
    this.getDicts('follow_state').then(response => {
      this.followStateOptions = response.data
    })
    this.getDicts('tube_type').then(response => {
      this.tubeTypeOptions = response.data
    })
    this.getActiveLabelTemp()
  },
  methods: {
    // 创建样本源附件上传子组件回调
    fileUploadEvent(fileList) {
      this.createForm.attaches = fileList
    },
    // 获取当前启用的标签模板
    getActiveLabelTemp() {
      getActiveTemp().then(response => {
        this.activeLabelTemp = response.data
      })
    },
    // 打印条码
    handlePrint() {
      if (!this.selectSamples || this.selectSamples.length === 0) {
        this.$message.warning('请先选择需打印项')
        return false
      }
      if (!this.activeLabelTemp || !this.activeLabelTemp.labelTempContent) {
        this.$message.warning('当前不存在启用的打印模板')
        return false
      }

      let value = {}
      value.title = this.activeLabelTemp.labelTempName
      value.width = this.activeLabelTemp.labelWidth
      value.height = this.activeLabelTemp.labelHeight
      value.pageWidth = this.activeLabelTemp.labelPageWidth
      value.pageHeight = this.activeLabelTemp.labelPageHeight
      value.tempItems = JSON.parse(this.activeLabelTemp.labelTempContent).tempItems
      // this.$lodop.print(value, this.selectSamples);
      this.$lodop.preview(value, this.selectSamples)
    },
    /** 查询样本类型 列表 */
    getSampleTypeList() {
      listSampleType().then(response => {
        this.sampleTypeOptions = this.handleTree(response.data, 'sampTypeId', 'parentId')
      })
    },
    /** 转换样本类型 数据结构 */
    normalizerSampType(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.sampTypeId,
        label: node.sampTypeName,
        children: node.children
      }
    },
    /** 查询样本组 列表 */
    getSampleGroupList() {
      listSampleGroup().then(response => {
        this.sampleGroupOptions = this.handleTree(response.data, 'sampGroupId', 'parentId')
      })
    },
    /** 转换样本组 数据结构 */
    normalizerSampGroup(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.sampGroupId,
        label: node.sampGroupName,
        children: node.children
      }
    },
    /** 查询样本源类型 列表 */
    getSourceTypeList() {
      listSourceType().then(response => {
        this.sourceTypeOptions = this.handleTree(response.data, 'sourceTypeId', 'parentId')
      })
    },
    /** 转换样本源类型 数据结构 */
    normalizerSourceType(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.sourceTypeId,
        label: node.sourceTypeName,
        children: node.children
      }
    },
    /** 样本状态状态字典翻译 */
    sampStateFormat(row, column) {
      return this.selectDictLabel(this.sampStateOptions, row.sampState)
    },
    /** 随访状态字典翻译 */
    followStateFormat(row) {
      return this.selectDictLabel(this.followStateOptions, row.followState)
    },
    /** 冻存管类型字典翻译 */
    tubeTypeFormat(row) {
      return this.selectDictLabel(this.tubeTypeOptions, row.tubeType)
    },
    /** 查询样本复份 列表 */
    getList() {
      this.loading = true
      listSample(this.queryParams).then(response => {
        this.sampleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sampBackupId)
      this.selectSamples = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleCreate() {
      this.createReset()
      this.createOpen = true
    },
    submitCreateForm() {
      if (this.createForm.formKey) {
        let custFormRef = this.$refs.formCustom[0]
        let custForm = custFormRef.$refs[custFormRef.formConf.formRef]
        let custData = custFormRef[custFormRef.formConf.formModel]
        let custDesc = {}
        for (let onceForm of this.createForm.formJson) {
          for (let onceField of onceForm.json.fields) {
            if (onceField.__vModel__) {
              custDesc[onceField.__vModel__] = onceField.__config__.label
            } else {
              if (onceField.__config__ && onceField.__config__.children && onceField.__config__.children.length > 0) {
                onceField.__config__.children.forEach(child => {
                  custDesc[child.__vModel__] = child.__config__.label
                })
              }
            }
          }
        }
        let formDataDto = { data: custData, desc: custDesc }
        // 自定义表单的核验
        custForm.validate(e => {
          if (e) {
            this.createForm.formDataSaveDto = formDataDto
          }
        })
      }

      this.$refs['createForm'].validate(valid => {
        if (valid) {
          createSample(this.createForm).then(response => {
            this.msgSuccess('新增成功')
            this.createOpen = false
            this.createReset()
            this.getList()
          })
        }
      })
    },
    cancelCreate() {
      this.createOpen = false
      this.createReset()
    },
    /** 获取样本源详情 */
    getSourceDetail(content) {
      getSourceByCode(content).then(response => {
        if (response.data && Object.keys(response.data).length > 0) {
          this.createForm.sourceId = response.data.sourceId
          this.createForm.sourceName = response.data.sourceName
          this.createForm.sourceDesc = response.data.sourceDesc
          this.createForm.attaches = response.data.attaches
          this.createForm.followState = response.data.followState
          this.createForm.sourceTypeId = response.data.sourceTypeId
          this.createForm.formKey = response.data.formKey
          this.createForm.formDesc = response.data.formDesc
          this.createForm.formData = response.data.formData
          this.showFormJson(this.createForm.formKey)
        } else {
          this.createForm.sourceId = undefined
          this.createForm.sourceName = undefined
          this.createForm.sourceDesc = undefined
          this.createForm.followState = undefined
          this.createForm.sourceTypeId = undefined
          this.createForm.formKey = undefined
          this.createForm.formDesc = undefined
          this.createForm.formData = undefined
        }
      })
    },
    // 样本源类型下拉框选择事件
    sourceTypeSelect(node, instanceId) {
      this.createForm.formKey = node.formKey
      this.showFormJson(node.formKey)
    },
    /**动态表单展示 */
    showCustomForm(formKey, formData) {
      if (!formKey || formKey === '') {
        this.$set(this.form, 'formJson', undefined)
        return false
      }
      formJsonShow(formKey).then(response => {
        let formJson = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formJson.push({
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.$set(this.form, 'formJson', formJson)
        this.disableForm(this.form.formJson[0].json)
        if (formData != undefined) {
          this.fillFormData(this.form.formJson[0].json, JSON.parse(formData))
          this.$set(this.form, 'formJson', formJson)
        }
      })
    },
    // 渲染动态表单
    showFormJson(formKey) {
      formJsonShow(formKey).then(response => {
        let formJson = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formJson.push({
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.$set(this.createForm, 'formJson', formJson)
        if (this.createForm.formData != undefined) {
          this.fillFormData(this.createForm.formJson[0].json, JSON.parse(this.createForm.formData))
          this.$set(this.createForm, 'formJson', formJson)
        }
      })
    },
    // 动态表单值回写
    fillFormData(form, data) {
      form.fields.map(item => {
        if (item.__vModel__) {
          const val = data[item.__vModel__]
          if (val) {
            item.__config__.defaultValue = val
          }
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              const childVal = data[child.__vModel__]
              if (childVal) {
                child.__config__.defaultValue = childVal
              }
            })
            return item
          }
        }
      })
    },
    // 设置动态表单禁用状态
    disableForm(form) {
      form.fields.map(item => {
        if (item.__vModel__) {
          item.disabled = true
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              child.disabled = true
            })
            return item
          }
        }
      })
    },
    // 样本类型下拉框选择事件
    sampleTypeSelect(node, instanceId) {
      getSampleType(node.sampTypeId).then(response => {
        if (response.data) {
          this.$set(this.createForm, 'sampQuantity', response.data.sampTypeDefaultQuantity)
          this.createForm.sampUnit = response.data.sampTypeDefaultUnit
          this.createForm.sampBackupCount = response.data.sampTypeDefaultDuplqty
        }
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset()
      const sampBackupId = row.sampBackupId || this.ids
      this.open = true
      this.title = '样本复份详情'
      getSample(sampBackupId).then(response => {
        this.form = response.data
      })
      // 获取样本复份生命周期
      getSampleLifeCycle(sampBackupId).then(response => {
        this.lifeCycles = response.data
      })
      // 获取同样本其他复份信息
      getSameSamples(row).then(response => {
        this.sameSamples = response.data
      })
      // 获取样本源信息及自定义表单
      getSampSourceInfo(row.sampSourceId).then(response => {
        this.sampSourceInfo = response.data
        //渲染自定义表单
        const formKey = this.sampSourceInfo.formKey
        const formData = this.sampSourceInfo.formData
        this.formData = this.formData
        this.showCustomForm(formKey, formData)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.sampBackupId != null) {
            updateSample(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addSample(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有样本复份 数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(function() {
        return exportSample(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '样本信息导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      getImportTemplate().then(response => {
        this.download(response.msg)
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 表单重置
    reset() {
      this.form = {
        sampBackupId: undefined,
        sampId: undefined,
        sampBackupCode: undefined,
        sampState: undefined,
        sampQuantity: undefined,
        sampUnit: undefined,
        sampleBackupSeq: undefined,
        sampLocation: undefined,
        sampFreezeThawCount: undefined,
        samplingTime: undefined,
        qrCode: undefined,
        tubeType: undefined,
        stockState: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      }
      this.resetForm('form')
      this.lifeCycles = []
    },
    createReset() {
      this.createForm = {
        sourceId: undefined,
        sourceCode: undefined,
        sourceName: undefined,
        sourceDesc: undefined,
        attaches: undefined,
        followState: undefined,
        sourceTypeId: undefined,
        formKey: undefined,
        formJson: undefined,
        formDesc: undefined,
        formData: undefined,
        sampTypeId: undefined,
        sampGroupId: undefined,
        sampQuantity: undefined,
        sampUnit: undefined,
        sampBackupCount: undefined,
        tubeType: undefined,
        samplingTime: undefined,
        formDataSaveDto: undefined
      }
      this.resetForm('createForm')
    }
  }
}
</script>
<style scoped>
.samp-label {
  width: 100px;
  font-weight: 700;
  text-align: right;
  vertical-align: middle;
  font-size: 14px;
  line-height: 30px;
  display: inline-block;
}

.samp-value {
  font-weight: 100;
  text-align: center;
  vertical-align: middle;
  font-size: 14px;
  line-height: 30px;
  margin-left: 36px;
}

/deep/ .el-form-item__content {
  line-height: 36px;
}

.el-divider--vertical {
  display: inline-block;
  height: 20em;
  border-left: 2px dashed #e8eaec;
  position: relative;
  background: 0 0;
}

/deep/ .el-scrollbar__wrap {
  overflow: scroll;
  width: 110%;
  height: 100%;
}

.el-scrollbar {
  display: flex;
  justify-content: space-around;
  padding: 0 10px;
}

.el-scrollbar__bar.is-horizontal {
  display: none;
}

</style>
